package com.shiguiwu.springmybatis.designpattern.observe.event;

import com.shiguiwu.springmybatis.designpattern.observe.LotteryResult;
import com.shiguiwu.springmybatis.designpattern.observe.event.listener.EventListener;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: 事件管理器
 * @author: stone
 * @date: Created by 2021/9/3 15:02
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.designpattern.observe.event
 */
@Slf4j
public class EventManager {

    private Map<Enum<EventType>, List<EventListener>> listeners = new ConcurrentHashMap<>();

    @SafeVarargs
    public EventManager(Enum<EventType>... options) {
        for (Enum<EventType> option : options) {
            listeners.put(option, new ArrayList<>());
        }
    }


    /**
     * 发布订阅
     *
     * @param option
     * @param listener
     */
    public void subscribe(Enum<EventType> option, EventListener listener) {
        List<EventListener> eventListeners = listeners.get(option);
        eventListeners.add(listener);
    }


    /**
     * 取消发布订阅
     *
     * @param option
     * @param listener
     */
    public void unSubscribe(Enum<EventType> option, EventListener listener) {
        List<EventListener> eventListeners = listeners.get(option);
        eventListeners.remove(listener);
    }

    /**
     * 触发消息
     * @param eventType
     * @param lotteryResult
     */
    public void notify(Enum<EventType> eventType, LotteryResult lotteryResult) {
        List<EventListener> eventListeners = listeners.get(eventType);
        eventListeners.forEach(e -> {
            e.onEvent(lotteryResult);

        });
    }




    public enum EventType {
        MQ,Message
    }
}
